<template>
  <div class="take_stock">
    <div class="take_stock-search">
      <div class="take_stock-search-top">
        <el-form ref="ruleFormRef" :model="formData" style="width: 100%">
          <div class="item">
            <el-form-item label="盘点标题">
              <el-input v-model="formData['checkTitle']"></el-input>
            </el-form-item>
          </div>
          <div class="item">
            <el-form-item label="状态">
              <el-select v-model="formData['checkState']" placeholder="">
                <el-option v-for="item in checkStateList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="item">
            <el-form-item label="盘点仓库">
              <el-select v-model="formData['warehouseId']" placeholder="">
                <el-option v-for="item in warehouseList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="item">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="formData['createTime']"
                value-format="YYYY-MM-DD hh:mm:ss"
                type="daterange"
                placeholder="日期"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 40%"
                @change="handelChangeTime"
              />
            </el-form-item>
          </div>
          <div class="item btn">
            <el-form-item>
              <el-button :icon="Search" type="primary" @click="handelClickSerch">查询</el-button>
              <el-button type="primary" plain :icon="RefreshLeft" @click="resetForm">重置</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="take_stock-search-botton">
        <div>
          <tabel-View :list="data.list" @update="getTime"></tabel-View>
        </div>
        <div>
          <el-button
            type="primary"
            @click="
              () => {
                optionInfo.isShow = true;
              }
            "
            >新建盘点明细</el-button
          >
        </div>
      </div>
    </div>
    <div class="take_stock-tabel">
      <div class="take_stock-tabel-content">
        <el-table :data="data.takeData" style="width: 100%" height="100%" class="jzt-table" stripe>
          <el-table-column prop="checkCode" label="单据编码" width="150" />
          <el-table-column prop="checkTitle" label="盘点标题" width="150" />
          <el-table-column prop="warehouseName" label="仓库" width="150" />
          <el-table-column prop="checkState" label="盘点状态" width="150">
            <template #default="scope">
              <p class="status" :style="{ color: status(scope.row.checkState), background: statusBck(scope.row.checkState) }">
                {{ useCodeArrStore().getDictName("check_state", scope.row.checkState) }}
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="150" />
          <el-table-column prop="eproductNum" label="账面库存数量" width="150" />
          <el-table-column prop="eproductPartNum" label="账面库存件数" width="150" />
          <el-table-column prop="factProductNum" label="实盘库存数量" width="150" />
          <el-table-column prop="factProductPartNum" label="实盘库存件数" width="150" />
          <el-table-column prop="dispProductNum" label="盈亏数量" width="150">
            <template #default="scope">
              <p class="profit_and_loss">
                <span>
                  <span>{{ scope.row.dispProductNum }}</span>
                </span>
                <img :src="Number(scope.row.dispProductNum) < 0 ? dow : Number(scope.row.dispProductNum) == 0 ? '' : up" alt="" />
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="dispProductPartNum" label="盈亏件数" width="150">
            <template #default="scope">
              <p class="profit_and_loss">
                <span>
                  <span>{{ scope.row.dispProductPartNum }}</span>
                </span>
                <img
                  :src="Number(scope.row.dispProductPartNum) < 0 ? dow : Number(scope.row.dispProductPartNum) == 0 ? '' : up"
                  alt=""
                />
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="buyMoney" label="账面采购金额" width="150" />
          <el-table-column prop="dispBuyMoney" label="盈亏采购金额" width="150">
            <template #default="scope">
              <p class="profit_and_loss">
                <span>
                  <span>{{ scope.row.dispBuyMoney }}</span>
                </span>
                <img :src="Number(scope.row.dispBuyMoney) < 0 ? dow : Number(scope.row.dispBuyMoney) == 0 ? '' : up" alt="" />
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="tenantName" label="盘点人" width="150" />
          <el-table-column prop="remark" label="备注" width="224">
            <template #default="scope">
              <RemarkEditor v-model="scope.row.remark" :isEdit="false" />
            </template>
          </el-table-column>
          <el-table-column fixed="right" prop="date" label="操作" width="230">
            <template #default="scope">
              <el-button
                link
                class="ml0"
                size="small"
                type="primary"
                @click="handleEenter(scope.row)"
                v-if="scope.row.checkState == 2 || scope.row.checkState == 1"
                >录入</el-button
              >
              <el-button
                link
                class="ml0"
                size="small"
                type="primary"
                @click="toPath(`/procure/inventory-count/detail?checkId=${scope.row.checkId}`)"
                >详情</el-button
              >
              <el-popconfirm title="确定删除?" @confirm="handleDelete(scope.row.checkId)">
                <template #reference>
                  <el-button
                    class="ml0"
                    link
                    size="small"
                    type="primary"
                    v-if="scope.row.checkState == 2 || scope.row.checkState == 1"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
              <el-button
                link
                class="ml0"
                size="small"
                type="primary"
                @click="toPath(`/procure/inventory-count/inventory?checkId=${scope.row.checkId}`)"
                v-if="scope.row.checkState == 2 || scope.row.checkState == 1"
                >清单打印</el-button
              >
              <el-button
                class="ml0"
                type="primary"
                link
                size="small"
                :disabled="downloadLoading"
                @click="clickDdownload(scope.row)"
              >
                导出
              </el-button>
            </template>
          </el-table-column>
          <template #empty>
            <div style="text-align: center; padding: 20px">
              <el-empty description="这里暂时什么都没有" />
            </div>
          </template>
        </el-table>
      </div>
      <div class="take_stock-tabel-pagination">
        <el-pagination
          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :size="size"
          :disabled="disabled"
          :background="data.background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <createCountTypeDialog
      :optionInfo="optionInfo"
      @close="
        () => {
          optionInfo.isShow = false;
        }
      "
    />
  </div>
</template>

<script setup>
// 资源导入
import { ref, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import { Search, RefreshLeft } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import useCodeArrStore from "@/store/modules/select";
import dow from "@/static/images/dow.png";
import up from "@/static/images/up.png";
// import dayjs from "dayjs";
// api
import { getlistByTenantId, getList, checkDelete, checkDownload } from "@/apis/procure/inventory-count";
// 组件
import createCountTypeDialog from "./components/createCountTypeDialog";
import tabelView from "./components/tabel.vue";
import RemarkEditor from "@/components/RemarkEditor";
const optionInfo = ref({ isShow: false });
const useRoutPath = useRouter();
// 表单查询的数据
const formData = ref({});
const ruleFormRef = ref();
const checkStateList = ref([
  { label: "未盘点", value: "1" },
  { label: "盘点中", value: "2" },
  { label: "盘点完成", value: "3" },
  { label: "已调账", value: "4" }
]);
const warehouseList = ref([]);
const data = reactive({
  background: false,
  currentPage: 1,
  pageSize: 10,
  list: [
    { name: "今天", value: "1" },
    { name: "昨天", value: "2" },
    { name: "近7天", value: "3" },
    { name: "近30天", value: "4" }
  ],
  takeData: [],
  total: 0
});

const toPath = obj => {
  //打开新页签
  const routeUrl = useRoutPath.resolve(obj);
  window.open(routeUrl.href, "_blank");
};
// 获取仓库信息
const getlistByTenantIds = () => {
  getlistByTenantId().then(res => {
    let arr = [];
    res.data.map(it => {
      arr.push({ label: it.warehouseName, value: it.warehouseId });
    });
    warehouseList.value = arr;
  });
};
// 颜色
const status = n => {
  switch (n) {
    case 1:
      return "#FF9900";
    case 2:
      return "#007DFF";
    case 3:
      return "#007DFF";
    case 4:
      return "#14C85C";
    default:
      break;
  }
};
const statusBck = n => {
  switch (n) {
    case 1:
      return "#FFF0D9";
    case 2:
      return "#D9EDFF";
    case 3:
      return "#D9EDFF";
    case 4:
      return "#E3F9E9";
    default:
      break;
  }
};
const downloadLoading = ref(false);

const clickDdownload = row => {
  downloadLoading.value = true;

  checkDownload({ checkId: row.checkId }).then(res => {
    let url = window.URL.createObjectURL(res);
    const a = document.createElement("a");
    a.href = url;
    a.download = "库存盘点.xlsx";
    a.click();
    URL.revokeObjectURL(url);
    downloadLoading.value = false;
  });
};

// 获取时间昨天今天近期时间
const getTime = (start, end) => {
  formData.value.createTime = [start, end];
  getLists();
};
// 时间修改事件
const handelChangeTime = v => {
  formData.value.createTime = [v[0].split(" ")[0] + " 00:00:00", v[1].split(" ")[0] + " 23:59:59"];
};
const resetForm = () => {
  formData.value = {};
  getLists();
};
// 获取表格列表数据
const getLists = () => {
  let obj = JSON.stringify(formData.value);
  let obj1 = JSON.parse(obj);
  delete obj1.createTime;
  if ("createTime" in formData.value) {
    obj1.startCreateTime = formData.value.createTime[0];
    obj1.endCreateTime = formData.value.createTime[1];
  }
  let parms = {
    page: data.currentPage,
    size: data.pageSize,
    ...obj1
  };
  getList(parms)
    .then(res => {
      console.log(res);
      if (res.code == 200) {
        data.takeData = res.data.records;
        data.total = res.data.total;
      }
    })
    .catch(err => {
      console.log(err);
    });
};
// 查询
const handelClickSerch = () => {
  getLists();
};
// 分页事件
const handleSizeChange = v => {
  data.pageSize = v;
  getLists();
};
const handleCurrentChange = v => {
  data.currentPage = v;
  getLists();
};
// 删除盘点清单
const handleDelete = id => {
  checkDelete(id).then(res => {
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
      getLists();
    }
  });
};
// 录入
const handleEenter = item => {
  toPath({
    path: "/procure/inventory-count/enter",
    query: {
      checkId: item.checkId
    }
  });
};
onMounted(() => {
  getlistByTenantIds();
  getLists();
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
